<?php

namespace app\index\controller\v1\wechat;

use app\common\controller\WechatController;
use app\common\model\diy\Diy;
use hiduoke\services\facade\WechatService;
use think\App;
use think\facade\Cache;

class User extends WechatController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function index()
    {
        WechatService::getUser(false);
        $this->assign('assign', 'assig1n');
        return $this->fetch("index", ['user' => '渲染了User']);
    }

    public function oauth()
    {
        $this->assign('title', ' ');
        $user = WechatService::getUser(false);
//        $back_id = input('back_id', '');
        $back_url = input('back_url','');
//        var_dump($back_url);exit();
//        $url = Cache::get($back_id);
        if ($user) {
//            Cache::delete($back_id);
            to($back_url);
        }
        if (input('force', '0')) {
            WechatService::getUser();
        }
        return $this->fetch();
    }

    public function getUserInfo()
    {
        $user = WechatService::getUser(false);
        return $this->success('', $user);
    }

    public function getPosterData()
    {
        $user = WechatService::getUser(false);
        $url = $this->request->url();
        return $this->success('', ['user' => $user, 'url' => $url]);
    }

    public function getUserInfoForce($back_url = '')
    {
        $user = WechatService::getUser(false);
        if ($user) {
            return $this->success('', $user);
        } else {
            $url = url(config('hiduoke.wechat_app') . '/user/oauth', [
                'force'    => 1,
                'p'        => get_plaid(),
                'back_url' => $back_url,
            ])->domain(true)->build();
            return $this->error('', ['url' => $url]);
        }
    }

    public function getDiy()
    {
        $Diy = new Diy();
        $user_diy = $Diy->where(['key' => 'user', 'type' => 'wechat'])->find();
        if (!$user_diy) {
            return $this->error('error');
        }
        $data = $user_diy->value;
        $rule = $data['rule'];
        $dk_rule = [];
        foreach ($rule as $key => $value) {
            if (isset($value['setting'])) {
                $dk_rule[$key] = array(
                    'display'  => true,
                    'hidden'   => false,
                    'props'    => ['setting' => $value['setting']],
                    'type'     => "dkRow",
                    'children' => [$value]
                );
            } else {
                $dk_rule[$key] = $value;
            }

        }
        $data['rule'] = $dk_rule;

        return $this->success('ok', $data);
    }
}
